package action.back;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import models.Module;
import models.User;
import net.sf.json.JSONArray;
import service.IndexService;
import utils.StringHelper;
import utils.WebUtils;
import action.vo.LoginInfo;
import config.Constant;



public class IndexAction extends BaseAction{
	
	
	@Autowired
	private IndexService indexService;
	
	public String user(){
		String page = indexService.userData(request);
		return page;
	}
	
	public String home(){
		WebUtils.setNoCacheHeader(response);
		if(!auth())return APP_LOGIN;
		return "home";
	}
	
	
	public String top(){
		
		return "top";
	}
	/**
     * 获取主菜单
     */
    @SuppressWarnings("unchecked")
	public void getMainMenus() throws Exception{
    	String moduleCode = request.getParameter("moduleCode");
    	
    	String asRoot = request.getParameter("asRoot");
    	
    	Module rootModule = null;
    	if(StringUtils.isNotEmpty(moduleCode)){
    		rootModule = getCommonService().getByProperty(Module.class, "code", moduleCode);
    	}
    	
    	LoginInfo info = super.getLoginInfo();
    	List<Module> modules = new ArrayList<Module>();
    	if(!Constant.SHOW_ALL_CATEGORG){
    		User user = info.getUser();
    		List<Integer> roleids = commonService.findAll("select e.role.id from UserRole e where e.user = ?",user);
    		if(roleids.size()>0){
    			if(rootModule==null)
    				modules = commonService.findAll("select rm.module from RoleModule rm where rm.module.parent is null and rm.role.id in ("+StringHelper.join(roleids.toArray(new Integer[0]), ",")+") order by rm.module.position asc");
    			else{
    				if(!StringHelper.parseBoolean(asRoot)){
    					modules = commonService.findAll("select rm.module from RoleModule rm where rm.module = ? and rm.role.id in ("+StringHelper.join(roleids.toArray(new Integer[0]), ",")+") order by rm.module.position asc",rootModule);
    				}
    				else{
    					modules = commonService.findAll("select rm.module from RoleModule rm where rm.module.parent = ? and rm.role.id in ("+StringHelper.join(roleids.toArray(new Integer[0]), ",")+") order by rm.module.position asc",rootModule);
    				}
    			}
    				
    		}
        }
    	else{
    		if(rootModule==null)
    			modules = commonService.findAll("from Module where parent is null or parent.id=0 order by position asc");
    		else{
    			if(!StringHelper.parseBoolean(asRoot)){
    				modules = commonService.findAll("from Module where parent =? order by position asc",rootModule);
    			}
    			else{
    				modules = commonService.findAll("from Module where id =? order by position asc",rootModule.getId());
    			}
    		}
    			
    	}
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for(Module module : modules){
        	
        	Map<String,Object> tree = new HashMap<String,Object>();
        	 tree.put("id", module.getId());
             tree.put("title", module.getName());
             tree.put("leaf", false);
             tree.put("ifFunc", StringHelper.parseBoolean(module.getIfFunc()));
             if(StringUtils.isNotEmpty(module.getFuncUrl()))
            	 tree.put("funcUrl", module.getFuncUrl());
             list.add(tree);
        }
       
        JSONArray jsonObject = JSONArray.fromObject(list);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
    }
    
    
    /**
     * 获取指定主菜单的树菜单
     */
    @SuppressWarnings("unchecked")
	public void getTreeMenus() throws Exception{
    	
        Integer moduleId = Integer.parseInt(request.getParameter("moduleId"));
        LoginInfo info = super.getLoginInfo();
       
    	
    	List<Module> modules = new ArrayList<Module>();
    	List<Module> functions = new ArrayList<Module>();
    	if(!Constant.SHOW_ALL_CATEGORG){
    		User user = info.getUser();
    	    List<Integer> roleids = commonService.findAll("select e.role.id from UserRole e where e.user = ?",user);
    		if(roleids.size()>0){
        		modules   = commonService.findAll("select rm.module from RoleModule rm where rm.module.ifFunc=? and rm.module.parent.id=? and rm.role.id in ("+StringHelper.join(roleids.toArray(new Integer[0]), ",")+") order by rm.module.position asc",Constant.FALSE, moduleId);
            	functions = commonService.findAll("select rm.module from RoleModule rm where rm.module.ifFunc=? and rm.module.parent.id=? and rm.role.id in ("+StringHelper.join(roleids.toArray(new Integer[0]), ",")+") order by rm.module.position asc",Constant.TRUE,moduleId);
        	}
        }
    	else{
    		if(!Constant.IGNORE_BLANK_URL_CATEGORG){
    			modules   = commonService.findAll("from Module where ifFunc=? and parent.id=? order by position asc",Constant.FALSE, moduleId);
        		functions = commonService.findAll("from Module where ifFunc=? and parent.id=? order by position asc",Constant.TRUE, moduleId);
    		}
    		else{
    			modules   = commonService.findAll("from Module where ifFunc=? and parent.id=?  order by position asc",Constant.FALSE, moduleId);
        		functions = commonService.findAll("from Module where ifFunc=? and parent.id=? order by position asc",Constant.TRUE, moduleId);
    		}
    		
    	}
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for(Module module : modules){
        	if(Constant.IGNORE_BLANK_URL_CATEGORG && ((StringHelper.parseBoolean(module.getIfFunc()) || module.getSubModuleCount() + module.getSubFunctionCount()==0)&& StringUtils.isEmpty(module.getFuncUrl()))){
        		continue;
        	}
        	Map<String,Object> tree = new HashMap<String,Object>();
        	tree.put("id", module.getId());
            tree.put("text", module.getName());
            tree.put("leaf", module.getSubFunctionCount()+module.getSubModuleCount()==0);
            tree.put("ifFunc", StringHelper.parseBoolean(module.getIfFunc()));
            if(StringUtils.isNotEmpty(module.getFuncUrl()))
           		tree.put("funcUrl", module.getFuncUrl());
            list.add(tree);
        }
        for(Module function : functions){
        	if(Constant.IGNORE_BLANK_URL_CATEGORG && (StringHelper.parseBoolean(function.getIfFunc()) && StringUtils.isEmpty(function.getFuncUrl()))){
        		continue;
        	}
        	Map<String,Object> tree = new HashMap<String,Object>();
        	tree.put("id", function.getId());
            tree.put("text", function.getName());
            tree.put("leaf", true);
            tree.put("ifFunc",true);
            tree.put("funcUrl", function.getFuncUrl());

            list.add(tree);
        }
        JSONArray jsonObject = JSONArray.fromObject(list);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
    }
}
